<?php
namespace Asf\Routing;

use Asf\Http\Response;
use Asf\Contracts\Http\Response as ResponseInterface;
use Asf\Util\Context;
use DI\Container;
use FastRoute\RouteCollector;
use Symfony\Component\Console\Logger\ConsoleLogger;

class Route
{
    protected $routeInfo;

    public static $container;

    public function __construct($routeInfo)
    {
        $this->routeInfo = $routeInfo;
    }

    /**
     * @return Response
     */
    public function run()
    {
        switch ($this->routeInfo[0]) {
            //如果路由未匹配
            case \FastRoute\Dispatcher::NOT_FOUND:
                $response = (new Response('', 404));

                break;
            //如果使用不允许的方法访问路由
            case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
                $allowedMethods = $this->routeInfo[1];
                // ... 405 Method Not Allowed
                break;
            //如果匹配到路由
            case \FastRoute\Dispatcher::FOUND:
                $handler = $this->routeInfo[1];
                $vars = $this->routeInfo[2];

                $response = self::$container->call($handler, $vars);
                break;
        }

        if ($response instanceof ResponseInterface) {
            return $response;
        }

        if (is_string($response)) {
            return new Response($response);
        } else {
            return new Response(var_export($response, true));
        }
    }

    //添加get路由
    public static function get($uri, $handler)
    {
        self::addRoute('GET', $uri, $handler);
    }

    //添加post路由
    public static function post($uri, $handler)
    {
        self::addRoute('POST', $uri, $handler);
    }

    //添加put路由
    public static function put($uri, $handler)
    {
        self::addRoute('PUT', $uri, $handler);
    }

    //添加delete路由
    public static function delete($uri, $handler)
    {
        self::addRoute('DELETE', $uri, $handler);
    }

    //添加head路由
    public static function head($uri, $handler)
    {
        self::addRoute('HEAD', $uri, $handler);
    }

    //添加resetful路由
    public static function resource($uri, $controller)
    {
         $uri = str_ends_with($uri, '/') ? substr($uri, 0, strlen($uri) - 1) : $uri;

        self::get($uri, [$controller, 'index']);
        self::get($uri . '/{id:\d+}', [$controller, 'show']);
        self::get($uri . '/create', [$controller, 'create']);
        self::get($uri . '/{id:\d+}/edit', [$controller, 'edit']);
        self::post($uri, [$controller, 'store']);
        self::put($uri . '/{id:\d+}', [$controller, 'update']);
        self::delete($uri . '/{id:\d+}', [$controller, 'delete']);
    }

    //添加任意类型的路由
    public static function addRoute($method, $uri, $handler)
    {
        /** @var RouteCollector $routeCollector */
        $routeCollector = self::$container->get(RouteCollector::class);
        $routeCollector->addRoute($method, $uri, $handler);
    }
}